import { messages } from 'share/common';
import React, { Component, PropTypes } from 'react';
import NewConsumerServer from './new-consumer-server';
import { Spin } from 'antd';
import moment from 'moment';
import 'styles/supplier-management/overview/consumer-other-setting.scss';
import {connect} from 'react-redux';

class ConsumerOtherSetting extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      resultData: {}, // 员工同步结果
      syncDepData: {}, // 部门同步结果
      rankName: false,
      depData: 'false',
      tempDepConfig: 'false',
      isEdit: false,
      isDepEdit: false
    };
    this.type = props.type;
  }

  componentWillMount() {
    this.updateAsyncResult();
    this.type === 'ctrip' && this.getEmployeeSynConfig();
    this.type === 'didi' && this.getDepSynConfig();
  }

  // 同步员工数据
  onSyncData = () => {
    NewConsumerServer(this).syncEmployeeData(this.type).then(res => {});
  };

  // 刷新同步结果
  updateAsyncResult = () => {
    NewConsumerServer(this).updateAsyncFailData(this.type).then((res) => {
      this.setState({ resultData: res.data });
    });
  };

  getEmployeeSynConfig = () => {
    NewConsumerServer(this).getRankNameConfig().then((res) => {
      this.setState({ rankName: res.data });
    });
  };

  saveEmployeeSynConfig = () => {
    const { rankName } = this.state;
    NewConsumerServer(this).saveRankNameConfig(rankName).then(() => {
      this.setState({
        rankName,
        isEdit: false
      });
    });
  };

  // 下载同步失败员工数据
  downloadFailData = () => {
    const { resultData } = this.state;
    NewConsumerServer(this).exportSyncFailData(this.type, resultData.batch).then((resp) => {
      if (resp.data && resp.data.exportFileRecord) {
        window.open(resp.data.exportFileRecord.tempUrl);
      }
    });
  };

  // 同步部门数据， 目前只支持滴滴
  onSyncDepData = () => {
    NewConsumerServer(this).syncDepData(this.type);
  };

  // 刷新部门同步结果
  updateSyncDepData = () => {
    const { company } = this.props;
    NewConsumerServer(this).updateSyncDepData(this.type, company.tenantId).then((res) => {
      this.setState({ syncDepData: res.data });
    });
  };

  getDepSynConfig = () => {
    const { company } = this.props;
    NewConsumerServer(this).getDepSynConfig(company.tenantId).then((res) => {
      this.setState({ depData: `${res.data[0].syncDepartmentFlag}`, tempDepConfig: `${res.data[0].syncDepartmentFlag}` });
    });
  };

  saveDepSynConfig = (value) => {
    const { company } = this.props;
    NewConsumerServer(this).saveDepSynConfig(company.tenantId, value).then((res) => {
      this.setState({
        depData: `${res.data[0].syncDepartmentFlag}`,
        tempDepConfig: `${res.data[0].syncDepartmentFlag}`,
        isDepEdit: false
      });
    });
  };

  // 下载同步失败部门信息
  downloadFailSyncDepData = () => {
    const { syncDepData } = this.state;
    NewConsumerServer(this).downloadFailSyncDepData(this.type, syncDepData.batch).then((resp) => {
      if (resp.data && resp.data.exportFileRecord) {
        window.open(resp.data.exportFileRecord.tempUrl);
      }
    });
  };

  failText = (data) => (
    <span className="default-color-inverse-font">{data.errorTotal || 0}</span>
  );

  static propTypes = {
    renderOtherUl: PropTypes.func,
    employeeSynContent: PropTypes.any,
    depSynContent: PropTypes.any,
    didiSettingContent: PropTypes.any
  };

  static defaultProps = {
    renderOtherUl: (sourceList) => sourceList.map((node) => node)
  };

  render() {
    const { resultData, loading } = this.state;
    const {
      renderOtherUl, employeeSynContent, depSynContent, didiSettingContent, ctripSetting, cmbcSetting
    } = this.props;
    const asyncUserList = [
      <li key="async">
        {' '}
        {messages('supplier.key296')/* 点击 */}
&nbsp;
        <a onClick={this.onSyncData}>{messages('supplier.key297')/* 同步员工数据 */}</a>
        &nbsp;
        {messages('supplier.key298')/* 可手工同步员工增量，同步需要时间，可先处理其他事物，之后回到该页面刷新结果 */}
      </li>,
      <li key="refresh">
        {' '}
        {messages('supplier.key296')/* 点击 */}
&nbsp;
        <a onClick={this.updateAsyncResult}>{messages('supplier.key299')/* 刷新 */}</a>
        &nbsp;
        {messages('supplier.key300')/* 可获取最近一次同步结果 */}
        ：
        {
          resultData.batch ? (
            <span>
              <sapn style={{ color: '#000' }}>
                {moment(new Date(parseInt(resultData.batch))).format('YYYY-MM-DD HH:mm')}
                {messages('supplier.key301', {
                  arg1: resultData.errorTotal + resultData.successTotal,
                  arg2: resultData.successTotal
                })/* 共同步完成{arg1}人，其中成功{arg2}人 */}
                ，
                {' '}
                {messages('supplier.key113')/* 失败 */}
                {this.failText(resultData)}
                {' '}
                {messages('supplier.key302')/* 人。 */}
              </sapn>
              {messages('supplier.key296')/* 点击 */}
&nbsp;
              <a onClick={this.downloadFailData}>
                {messages('supplier.key303')/* 下载同步失败员工信息 */}
              </a>
            </span>
          ) : messages('supplier.key446')/* 暂无同步结果 */
        }
      </li>
    ];
    return (
      <div className="consumer-other-setting">
        <div className="consumer-other-setting-card">
          <Spin spinning={loading}>
            {depSynContent && depSynContent(this)}
            <div className="consumer-other-setting-card-container">
              <h3>{messages('supplier.key295')/* 员工同步 */}</h3>
              <ul>
                {employeeSynContent && employeeSynContent(this)}
                {renderOtherUl(asyncUserList)}
              </ul>
            </div>
            {didiSettingContent && didiSettingContent(this)}
            {ctripSetting && ctripSetting}
            {cmbcSetting && cmbcSetting}
          </Spin>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  };
}
export default connect(mapStateToProps)(ConsumerOtherSetting);
